package org.llc.bpmn.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.llc.bpmn.model.po.PurchaseBpm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;

import org.llc.bpmn.mapper.PurchaseApplyMapper;

@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 5)
@Service
public class PurchaseBpmService {

    @Autowired
    PurchaseApplyMapper purchasemapper;

    @Autowired
    IdentityService identityservice;

    @Autowired
    RuntimeService runtimeservice;


    public ProcessInstance startWorkflow(String content, BigDecimal total, String userid, Map<String, Object> variables) {
        PurchaseBpm purchase = new PurchaseBpm();
        purchase.setApplyer(userid);
        purchase.setItemlist(content);
        purchase.setTotal(total);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        purchase.setApplytime(sdf.format(new Date()));
        //保存流程信息
        purchasemapper.save(purchase);
        String businesskey = String.valueOf(purchase.getId());//使用leaveapply表的主键作为businesskey,连接业务数据和流程数据
//        identityservice.setAuthenticatedUserId(userid);
        ProcessInstance instance = runtimeservice.startProcessInstanceByKey("purchase", businesskey, variables);
        String instanceid = instance.getId();
        purchase.setProcessinstanceid(instanceid);
        purchasemapper.updateByPrimaryKeySelective(purchase);
        return instance;
    }

    public List<PurchaseBpm> list(String username) {
        return purchasemapper.listPurchaseApplyByApplyer(username);
    }

    public List<PurchaseBpm> pageList(String username, int current, int rowCount) {
        PageHelper.startPage(current, rowCount);
        List<PurchaseBpm> list = purchasemapper.listPurchaseApplyByApplyer(username);
        return list;
    }

    public PurchaseBpm getPurchase(int id) {
        return purchasemapper.getPurchaseApply(id);
    }

    public void updatePurchase(PurchaseBpm a) {
        purchasemapper.updateByPrimaryKeySelective(a);
    }

}
